<template>
  <up-modal :show="show" title="切换身份" @cancel="handleCancel">
    <u-form :rules="rules" :model="formData" ref="formRef" label-width="6em">
      <u-form-item label="身份类型" prop="client_type">
        <u-input
          v-model="clientTypeLabel"
          readonly
          placeholder="请选择身份类型"
        >
          <template #suffix>
            <u-button type="primary" size="small" @click="pickerShow = true"
              >选择</u-button
            >
          </template>
        </u-input>
      </u-form-item>

      <u-form-item label="备注" prop="remark">
        <u-textarea v-model="formData.remark" placeholder="请输入备注信息" />
      </u-form-item>
    </u-form>

    <u-picker
      :show="pickerShow"
      :columns="clientTypeOptions"
      keyName="label"
      @cancel="pickerShow = false"
      @confirm="handleConfirm"
    ></u-picker>

    <template #confirmButton>
      <view class="flex gap-20">
        <u-button type="error" @click="handleCancel" size="small"
          >取消</u-button
        >
        <u-button type="primary" @click="handleSubmit" size="small"
          >确认</u-button
        >
      </view>
    </template>
  </up-modal>
</template>

<script setup>
import { switchAgentArea } from "@/common/apis/agent.js";
import { ref, defineProps, defineEmits, reactive } from "vue";
import { useStore } from "vuex";

const store = useStore();

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(["confirm", "cancel"]);

const clientTypeLabel = ref("");

const pickerShow = ref(false);

const formData = ref({
  agent: store.state.user.agentInfo?.id,
  client_type: "",
  remark: "",
});

const clientTypeOptions = reactive([
  [
    { label: "供应商", value: "supplier" },
    { label: "商户", value: "merchant" },
  ],
]);

const formRef = ref(null);

const rules = ref({
  client_type: [
    { required: true, message: "请选择客户类型", trigger: "change" },
  ],
  remark: [{ required: true, message: "请输入备注信息", trigger: "blur" }],
});

function handleConfirm(event) {
  const { value } = event;
  formData.value.client_type = value[0].value;
  clientTypeLabel.value = value[0].label;
  pickerShow.value = false;
}

function handleSubmit() {
  formRef.value
    .validate()
    .then(() => {
      emits("confirm", formData.value);
      switchAgentArea(formData.value);
      uni.$u.toast("提交成功，请登录管理员审核");
    })
    .catch((errors) => {
      console.error("表单验证失败:", errors);
    });
}

function handleCancel() {
  formRef.value.resetFields();
  emits("cancel");
}
</script>
